from pyramid_layout.panel import panel_config
from models.category import Category
from models.item import Item
from sqlalchemy import func
import time

@panel_config(name='categories',renderer='myproject:templates/panel/categories.jinja2')
def categories_panel(context,request):
    return {'categories':request.dbsession.query(Category).filter_by(parent=None).all()}

@panel_config(name='category',renderer='myproject:templates/panel/category.jinja2')
def category_panel(context,request,categroy_id):
    category = request.dbsession.query(Category).filter_by(id=categroy_id).first()
    category_old = request.dbsession.query(Category).filter_by(id=category.parent_id).first()
    if not category_old:
        category_old=category
    return {'category_old':category_old,'categroy_id':categroy_id}

@panel_config(name='item_bill',renderer='myproject:templates/panel/item_bill.jinja2')
def item_bill_panel(context,request,category_id=0):
    if category_id == 0:
        item_bills=request.dbsession.query(Item).order_by('num desc').limit(3).all()
    else:
        now_year_month = time.strftime('%Y-%m', time.localtime(time.time()))
        category = request.dbsession.query(Category).filter_by(id=category_id).first()
        category_old = request.dbsession.query(Category).filter_by(id=category.parent_id).first()
        if not category_old:
            cat_id_list = []
            for category_value in category.children:
                cat_id_list.append(category_value.id)
            item_bills = request.dbsession.query(Item).filter(Item.category_id.in_(cat_id_list), func.strftime('%Y-%m',Item.add_time) == now_year_month).order_by('num desc').limit(3).all()
        else:
            item_bills = request.dbsession.query(Item).filter(Item.category_id == category.id, func.strftime('%Y-%m',Item.add_time) == now_year_month).order_by('num desc').limit(3).all()

    return {'item_bills':item_bills}
